package org.jeecg.modules.outOrder1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.outOrder1.entity.OutOrder1;
import org.jeecg.modules.outOrder1.entity.OutOrderZi;
import org.jeecg.modules.outOrder1.mapper.OutOrderZiMapper;
import org.jeecg.modules.outOrder1.mapper.OutOrder1Mapper;
import org.jeecg.modules.outOrder1.service.IOutOrder1Service;
import org.jeecg.modules.outOrder1.service.IOutOrderZiService;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @Description: 出库单
 * @Author: jeecg-boot
 * @Date: 2024-01-12
 * @Version: V1.0
 */
@Service
public class OutOrder1ServiceImpl extends ServiceImpl<OutOrder1Mapper, OutOrder1> implements IOutOrder1Service {

    @Autowired
    private OutOrder1Mapper outOrder1Mapper;
    @Autowired
    private OutOrderZiMapper outOrderZiMapper;
    @Autowired
    private IOutOrderZiService outOrderZiService;
    @Autowired
    private IReportLabelService reportLabelService;

    @Override
//    @Transactional
    public void saveMain(OutOrder1 outOrder1, List<OutOrderZi> outOrderZiList) {
        int status;
        if (outOrder1.getArea() != null && outOrder1.getArea() == 1){//如果出库库区是备货暂存区，状态为已备货
            status = 8;
        } else {//否则状态为带备货
            status = 6;
        }
        outOrder1.setOutOrderStatus(status);
        outOrder1Mapper.insert(outOrder1);
        OutOrder1 order1 = this.getById(outOrder1.getId());
        if (outOrderZiList != null && !outOrderZiList.isEmpty() && outOrderZiList.get(0).getSkuCode() != null && !outOrderZiList.get(0).getSkuCode().isEmpty()) {
            //添加子表数据
            for (OutOrderZi entity : outOrderZiList) {
                //外键设置
                entity.setPid(order1.getId());
                entity.setOutOrderStatus(status);//子表状态
                entity.setPcsNum(entity.getBoxNum() * entity.getTrayNum() * entity.getPcs());//总件数
                outOrderZiMapper.insert(entity);
            }
            //命中库存
            LambdaQueryWrapper<OutOrderZi> outOrderZiLqw = Wrappers.lambdaQuery(OutOrderZi.class);
            outOrderZiLqw.eq(OutOrderZi::getPid, order1.getId());
            List<OutOrderZi> outOrderZis = outOrderZiMapper.selectList(outOrderZiLqw);
            for (OutOrderZi outOrderZi : outOrderZis) {
                //命中库存
                if (extracted(order1, outOrderZi)) {
                    //命中库存NG，恢复数据
                    LambdaUpdateWrapper<ReportLabel> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(ReportLabel::getOutOrderId, null);
                    if (order1.getArea() != null && order1.getArea() != 1) {//如果出库库区不是备货暂存区，状态为已上架
                        updateWrapper.set(ReportLabel::getStatus, 5);
                    }
                    updateWrapper.eq(ReportLabel::getStatus, status).eq(ReportLabel::getOutOrderId, order1.getId());
                    reportLabelService.update(updateWrapper);
                    LambdaUpdateWrapper<OutOrderZi> wrapper = Wrappers.lambdaUpdate();
                    wrapper.set(OutOrderZi::getOutOrderStatus, 11);
                    wrapper.eq(OutOrderZi::getPid, order1.getId());
                    outOrderZiService.update(wrapper);
                    return;
                }
            }
        }
    }

    /**
     * 重新命中
     */
    @Override
    @Transactional
    public void rehit(OutOrder1 order1, List<OutOrderZi> outOrderZiList) {
        int status;
        if (order1.getArea() != null && order1.getArea() == 1){//如果出库库区是备货暂存区，状态为已备货
            status = 8;
        } else {//否则状态为带备货
            status = 6;
        }
        OutOrder1 outOrder1 = this.getById(order1.getId());
        if (outOrderZiList != null && !outOrderZiList.isEmpty() && outOrderZiList.get(0).getSkuCode() != null && !outOrderZiList.get(0).getSkuCode().isEmpty()) {
            for (OutOrderZi entity : outOrderZiList) {
                //命中库存
                if (extracted(outOrder1, entity)) {
                    //命中库存NG，恢复数据
                    LambdaUpdateWrapper<ReportLabel> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(ReportLabel::getOutOrderId, null);
                    if (order1.getArea() != null && order1.getArea() != 1) {//如果出库库区不是备货暂存区，状态为已上架
                        updateWrapper.set(ReportLabel::getStatus, 5);
                    }
                    updateWrapper.eq(ReportLabel::getStatus, status).eq(ReportLabel::getOutOrderId, order1.getId());
                    reportLabelService.update(updateWrapper);
                    LambdaUpdateWrapper<OutOrderZi> wrapper = Wrappers.lambdaUpdate();
                    wrapper.set(OutOrderZi::getOutOrderStatus, 11);
                    wrapper.eq(OutOrderZi::getPid, order1.getId());
                    outOrderZiService.update(wrapper);
                    return;
                }
            }
        }
    }

    @Override
    public Integer getOutOrderCount() {
        return outOrder1Mapper.getOutOrderCount(new Date());
    }

    //命中库存
    private boolean extracted(OutOrder1 outOrder1, OutOrderZi entity) {
        //命中库存（1.查找合适标签；2.设置状态及出库单id）
        LambdaQueryWrapper<ReportLabel> reportLabelLqw = Wrappers.lambdaQuery(ReportLabel.class);
        if (outOrder1.getOutOrderType().equals(1)) {
            reportLabelLqw.eq(ReportLabel::getFoaming, 1);//是否发泡
        }
        reportLabelLqw.and(
                wrapper -> wrapper.eq(ReportLabel::getSkuCode1, entity.getSkuCode())
                        .or()
                        .eq(ReportLabel::getSkuCode2, entity.getSkuCode())
        );
//        reportLabelLqw.eq(ReportLabel::getCustomerCode, outOrder1.getCustomerCode());//客户
        reportLabelLqw.eq(ReportLabel::getBoxNum, entity.getBoxNum());//箱数
        reportLabelLqw.eq(ReportLabel::getPcs, entity.getPcs());//规格
        reportLabelLqw.eq(ReportLabel::getPackagingType, entity.getPackagingType());//包装类型
        reportLabelLqw.eq(ReportLabel::getSkuType, outOrder1.getSkuType());//货品种类
        reportLabelLqw.eq(ReportLabel::getInOrderType, outOrder1.getOutOrderType());//入库类型
        reportLabelLqw.isNull(ReportLabel::getOutOrderId);//出库单为空则标签为未被命中
        reportLabelLqw.eq(ReportLabel::getIsFreeze, 0);//为未冻结的货品
        if (outOrder1.getArea() != null && outOrder1.getArea() == 1){//如果出库库区是备货暂存区，状态为已备货
            reportLabelLqw.eq(ReportLabel::getStatus, 8);//为已备货的货品
            /*reportLabelLqw.eq(ReportLabel::getShelfCode, "备货暂存区");
            reportLabelLqw.eq(ReportLabel::getCompartmentCode, "备货暂存区");*/
        } else {
            reportLabelLqw.eq(ReportLabel::getStatus, 5);//为已上架的货品
        }

        //出库规则
        switch (outOrder1.getOutOrderRules()) {
            case 1:
                reportLabelLqw.orderByAsc(ReportLabel::getStackingDate);//入库日期先入先出
                break;
            case 2:
                reportLabelLqw.orderByAsc(ReportLabel::getProductionDate);//生产日期先入先出
                break;
            case 3:
                reportLabelLqw.eq(ReportLabel::getInvoiceNum, outOrder1.getInvoicenum());//发票号
                break;
            default:
                return true;
        }
        List<ReportLabel> reportLabels = reportLabelService.list(reportLabelLqw);
        //命中库存NG
        if (entity.getTrayNum() > reportLabels.size() || reportLabels.isEmpty()) {
            entity.setOutOrderStatus(11);
            outOrderZiMapper.updateById(entity);
            outOrder1.setOutOrderStatus(11);
            outOrder1Mapper.updateById(outOrder1);
            return true;
        }

        //命中库存OK
        List<ReportLabel> labelList = reportLabels.stream().limit(entity.getTrayNum()).peek(item -> {
            if (outOrder1.getArea() != 1) {//如果出库库区不是备货暂存区，状态为待备货
                item.setStatus(6);
            }
            item.setOutOrderId(outOrder1.getId());
        }).collect(Collectors.toList());
        reportLabelService.updateBatchById(labelList);
        return false;
    }

    @Override
    @Transactional
    public void updateMain(OutOrder1 outOrder1, List<OutOrderZi> outOrderZiList) {
        outOrder1Mapper.updateById(outOrder1);

        //1.先删除子表数据
        outOrderZiMapper.deleteByMainId(outOrder1.getId());

        //2.子表数据重新插入
        if (outOrderZiList != null && !outOrderZiList.isEmpty()) {
            for (OutOrderZi entity : outOrderZiList) {
                //外键设置
                entity.setPid(outOrder1.getId());
                outOrderZiMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
        outOrderZiMapper.deleteByMainId(id);
        outOrder1Mapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            outOrderZiMapper.deleteByMainId(id.toString());
            outOrder1Mapper.deleteById(id);
        }
    }

}
